import { Component, OnInit, Input, ElementRef, forwardRef } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
    template: `
        <div class="clain-image-upload" [ngStyle]="{width:clainWidth,height:clainHeight}">
            <input class="file" type="file" name="{{ clName }}" accept="image/gif,image/jpeg,image/jpg,image/png,image/svg" (change)="uploadImage($event)" />
            <i *ngIf="value" class="remove-image" (click)="removeValue()">╳</i>
            <div class="clain-upload-btn-box">
                <a target="_blank" href="{{ value }}" *ngIf="value">
                    <img src="{{value}}" class="upload-image" />
                </a>
                <div class="clain-upload-btn" *ngIf="!value && !showLoading" (click)="clickUpload($event)">
                    <font size="6">+</font>
                    <br /><span>{{clTitle}}</span>
                </div>
                <div class="clain-upload-btn" *ngIf="showLoading">
                    <div class="progress">
                        <span [ngStyle]="{ width: ev + '%' }"></span>
                    </div>
                    <p>{{ ev }}%</p>
                </div>
            </div>
        </div>
    `,
    selector: 'clain-image-upload',
    styleUrls: ['clain.imageUpload.scss'],
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => ClainImageUploadComponent),
            multi: true,
        },
    ],
})
export class ClainImageUploadComponent implements OnInit, ControlValueAccessor {
    @Input()
     clName = 'image';
    @Input()
     clainWidth = '15rem';
    @Input()
     clainHeight = '15rem';
    @Input()
     clMultiple: Boolean = false;
    @Input()
     clSize = 1;
    @Input()
     clUrl = '/api/updateImage.do';
    @Input()
     value: string;
    @Input()
     clTitle = '上传图片';
     showLoading: Boolean = false;
     ev = 0;
    constructor( private el: ElementRef) {}
    propagateChange = (_: any) => {};
    writeValue(value: string) {
        if (value) {
            this.value = value;
        }
    }

    registerOnChange(fn: any) {
        this.propagateChange = fn;
    }

    registerOnTouched(fn: any) {}

    ngOnInit() {
        if (this.clMultiple) {
            this.el.nativeElement.querySelector('.file').setAttribute('multiple', 'multiple');
        }
    }
    /**
     * uploadImage
     */
    public uploadImage(e) {
        const file = e.target.files[0];
        const { name, size, type } = file;
        if (size > this.clSize * 1024 * 1024) {
            // this.nzMessageService.error('图片大小超过限制,不能上传超过' + this.clSize + 'MB的图片');
            return;
        }
        const formData: any = new FormData();
        const xhr = new XMLHttpRequest();
        // formData.append('file', files);
        formData.append(this.clName, file);
        xhr.upload.onprogress = ev => {
            this.ev = parseInt((100 * ev.loaded) / ev.total + '');
        };
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                this.showLoading = false;
                if (xhr.status === 200) {
                    const data = JSON.parse(xhr.response);
                    this.value = data.data.url;
                    this.propagateChange(data.data.url);
                } else {
                    e.target.value = null;
                }
            }
        };
        
        xhr.open('POST', this.clUrl, true);
        console.log(localStorage.getItem('token'))
        if(localStorage.getItem('token')){
            const token = localStorage.getItem('token');
            xhr.setRequestHeader('Authorization', 'Bearer ' + token);
        }
        xhr.send(formData);
        this.showLoading = true;
    }
    public clickUpload() {
        this.el.nativeElement.querySelector('.file').click();
    }
    /**
     * removeValue 删除当前上传图片
     */
    public removeValue() {
        this.value = '';
        this.propagateChange('');
        this.el.nativeElement.querySelector('.file').value = null;
    }
    public getObjectURL(file: File): string {
        return window.URL.createObjectURL(file);
    }
}
